package com.poi.demopoi.common;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.poi.demopoi.common.constant.HttpStatus;
import com.poi.demopoi.common.page.*;
import com.poi.demopoi.utils.DateUtils;
import com.poi.demopoi.utils.R;
import com.poi.demopoi.utils.StringUtils;
import com.poi.demopoi.utils.sql.SqlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * web层通用数据处理
 *
 * @author ruoyi
 */
public class BaseController {
    protected final Logger logger = LoggerFactory.getLogger(BaseController.class);


    static String base64Security = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY=";

//    @Autowired
//    private RedisCache redisCache;


    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getCurrent();
        Integer pageSize = pageDomain.getSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }
    protected void startPage2() {
        PageDomain2 pageDomain = TableSupport2.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
//        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRecords(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }
    protected TableDataInfo2 getDataTable2(List<?> list) {
        TableDataInfo2 rspData = new TableDataInfo2();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected TableDataInfo getDataVoTable(List<?> list, List<?> target) {
        TableDataInfo rspData = new TableDataInfo();
//        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRecords(target);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }


    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
//    protected AjaxResult toAjax(int rows) {
//        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
//    }
    protected R toAjax2(int rows) {
        return rows > 0 ? R.ok() : R.error();
    }


    /**
     * 把vo类中String类型的参数的null值或"NULL","null"转化成空字符串
     *
     * @param obj
     * @return
     */
    public static Object getReflectObjectTransString(Object obj) throws Exception {
        Class<? extends Object> classz = obj.getClass();
        Field[] fields = classz.getDeclaredFields();
        for (Field field : fields) {
            if (String.class == field.getType()) {
                // 属性参数值首字母转成大写
                char[] cs = (field.getName()).toCharArray();
                cs[0] -= 32;
                String methodGetName = "get" + String.valueOf(cs);
                String methodSetName = "set" + String.valueOf(cs);
                Method getMethod = classz.getMethod(methodGetName, null);
                Method setMethod = classz.getMethod(methodSetName, String.class);
                Object value = getMethod.invoke(obj, null);
                if (null == value || "NULL".equals((String) value) || "null".equals((String) value)) {
                    setMethod.invoke(obj, "");
                }
            }
        }
        return obj;
    }


    /**
     * @param sortName  排序字段
     * @param sortState 排序
     */
    public static Map getSort(String sortName, String sortState) {
        Map<String, String> sortmap = new HashMap<>();
        String[] keys = sortName.split(",");
        String[] types = sortState.split(",");
        for (int i = 0; i < keys.length; i++) {
            sortmap.put(keys[i], types[i]);
        }
        Map<String, String> resultMap = new HashMap<>();
        for (Map.Entry<String, String> entry : sortmap.entrySet()) {
            String key = entry.getKey();
            resultMap.put(key, entry.getValue());
        }
        return resultMap;
    }
}
